<template>
  <div>
    <component
      :is="block.type"
      v-for="(block, index) in parsedBlocks"
      :key="index"
      v-bind="block.props"
    ></component>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineExpose } from 'vue'
import MarkdownIt from 'markdown-it'
import CustomLineChart from './CustomLineChart.vue' // 导入自定义组件
import { parseBlocks, parseAsJson, parseOptions } from './util'
import { MarkdownType } from './model'

const props = defineProps({
  markdown: {
    type: String,
    required: true,
  },
})

const md = new MarkdownIt()
const parsedBlocks = ref([])

const parseMarkdown = (markdown: string) => {
  const blocks = parseBlocks(markdown)

  // 处理每个块，生成最终的 parsedBlocks
  parsedBlocks.value = blocks.map(block => {
    if (block.type === MarkdownType.custom) {
      try {
        const jsonData = parseAsJson(block.content)
        const options = parseOptions(block.content)
        return {
          type: CustomLineChart,
          props: { data: jsonData, options },
        }
      } catch (err) {
        console.log(err)
      }
    }
    return {
      type: 'div',
      props: {
        innerHTML: md.render(block.content),
      },
    }
  })
}
const showMarkdown = (markdown: string) => {
  parsedBlocks.value = [
    {
      type: 'div',
      props: {
        innerHTML: md.render(markdown),
      },
    },
  ]
}

const loadParsedMarkdown = () => {
  parsedBlocks.value = []
  console.log('load-parsed-markdown')
  parseMarkdown(props.markdown)
}
watch(
  () => props.markdown,
  newMarkdown => {
    try {
      showMarkdown(newMarkdown)
    } catch (err) {
      console.log('DataChart load error', err)
    }
  },
  { immediate: true }
)
defineExpose({
  loadParsedMarkdown,
})
</script>
